package org.east.common.utils;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.east.common.exception.ApplicationException;

public class CsvFileUtils {

	/**
	 * 读取csv文件，以List形式返回每行数据
	 * csv文件含有标题,不会返回
	 * @param fileList
	 * @return
	 */
	public static List<List<String>> parseCsvFiles(List<File> fileList){
		List<List<String>> rList = new ArrayList<List<String>>();
		for(File f:fileList){
			DataInputStream in;
			try {
				in = new DataInputStream(new FileInputStream(f));
			} catch (FileNotFoundException e) {
				throw new ApplicationException("文件不存在:"+f.getAbsolutePath(),e);
			}
		    BufferedReader bufferedreader;
			try {
				bufferedreader = new BufferedReader(new InputStreamReader(in,"GBK"));
			} catch (UnsupportedEncodingException e) {
				try {
					in.close();
				} catch (IOException e1) {
					
				}
				throw new ApplicationException("不支持GBK编码",e);
			}
		    String stemp;   
		    String str;// 一个单元格
		    int count = 0;
		    try{
		    	//如果当前行不为空
		        while((stemp = bufferedreader.readLine()) != null){
		    	    if(stemp.startsWith("#")){
		    		    continue;
		    	    }
		            Pattern pCells = Pattern.compile("(\"[^\"]*(\"{2})*[^\"]*\")*[^,]*,");
		            Matcher mCells = pCells.matcher(stemp + ",");
		            List<String> cells = new ArrayList<String>();// 每行记录一个list
		            // 读取每个单元格
		        	 while (mCells.find()) {
	        		    str = mCells.group();
	        		    str = str.replaceAll("(?sm)\"?([^\"]*(\"{2})*[^\"]*)\"?.*,", "$1");
	        		    str = str.replaceAll("(?sm)(\"(\"))", "$2");
	        		    cells.add(str);
		        	 }
		        	 //标题不加入
		        	 if(count == 0){
		        		 count += 1;
		        	 }else{
		        		 rList.add(cells);
		        	 }

		        }
		        
		    } catch (IOException e){
		    	throw new ApplicationException("IO异常",e);
		    } finally{
		    	try {
					bufferedreader.close();
				} catch (IOException e) {
					
				}
		    }
		   
		}
		
		return rList;
	}
	
}
